/**
 * Copyright (C) 2015-2016 Guangzhou Xunhong Network Technology Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jxccp.ui.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.AnyRes;
import androidx.annotation.DrawableRes;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jxccp.im.callback.JXChatStateListener;
import com.jxccp.im.chat.common.entity.JXCommonQuestion;
import com.jxccp.im.chat.common.entity.JXSatisfication;
import com.jxccp.im.chat.common.entity.JXSatisfication.Option;
import com.jxccp.im.chat.common.message.ImageMessage;
import com.jxccp.im.chat.common.message.JXChatStateExtension;
import com.jxccp.im.chat.common.message.JXConversation;
import com.jxccp.im.chat.common.message.JXConversation.SessionStatus;
import com.jxccp.im.chat.common.message.JXMessage;
import com.jxccp.im.chat.common.message.JXMessage.ChatType;
import com.jxccp.im.chat.common.message.JXMessageAttribute;
import com.jxccp.im.chat.common.message.JXMessageUtil;
import com.jxccp.im.chat.common.message.LocationMessage;
import com.jxccp.im.chat.common.message.RichTextMessage;
import com.jxccp.im.chat.common.message.TextMessage;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.entities.JXOrderInfo;
import com.jxccp.ui.entities.ZhuiyiLoanOrderEntity;
import com.jxccp.ui.entities.ZhuiyiProductOrderEntity;
import com.jxccp.ui.listeners.JXChatFragmentListener;
import com.jxccp.ui.listeners.JXVoicePlayListener;
import com.jxccp.ui.model.JXEvaluateTask;
import com.jxccp.ui.model.JXEvaluateTask.JXEvaluteTaskCallback;
import com.jxccp.ui.model.JXRequestCusServiceTask.RequestCusServiceCallback;
import com.jxccp.ui.presenter.JXChatMsgBoxPresenter;
import com.jxccp.ui.presenter.JXChatPresenter;
import com.jxccp.ui.presenter.JXChatPresenterImp;
import com.jxccp.ui.utils.JXCommonUtils;
import com.jxccp.ui.view.adapter.JXChatAdapter;
import com.jxccp.ui.view.adapter.JXCommonQuestionListAdapter;
import com.jxccp.ui.view.adapter.JXEvaluateAdapter;
import com.jxccp.ui.view.adapter.JXInputAssociationAdapter;
import com.jxccp.ui.view.adapter.JXOrderListAdapter;
import com.jxccp.ui.view.adapter.JXQuickQuestionAdapter;
import com.jxccp.ui.view.adapter.ZhuiyiLoanOrderListAdapter;
import com.jxccp.ui.view.adapter.ZhuiyiProductOrderListAdapter;
import com.jxccp.ui.widget.JXInputMenuLayout;
import com.jxccp.ui.widget.JXInputMenuLayout.JXInputLayoutListener;
import com.jxccp.ui.widget.JXLinkMovementMethod;
import com.jxccp.ui.widget.JXVoiceHintView;
import com.jxccp.ui.widget.JXVoiceHintView.voiceRecorderCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.jxccp.ui.widget.JXInputMenuLayout.COMPOSING_STATE;
import static com.jxccp.ui.widget.JXInputMenuLayout.STOP_STATE;
import static com.jxccp.ui.widget.JXInputMenuLayout.VOICE_RECORDING_STATE;

public abstract class JXBaseChatFragment extends Fragment implements JXChatView, OnRefreshListener,
        OnTouchListener, View.OnClickListener, OnItemClickListener, JXChatFragmentListener, RequestCusServiceCallback {

    public static final int START_ASSOCIATION = 0;

    public static final int STOP_ASSOCIATION = 1;

    public String amapLoactionUrl = "http://uri.amap.com/marker?position=%s&name=%s&coordinate=gaode&callnative=0";

    protected Context mContext;

    /**
     * 界面是否可见
     */
    public boolean isVisiable;

    protected Handler mHandler;

    protected JXInputMenuLayout menuLayout;

    protected JXVoiceHintView voiceHintView;

    protected TextView titleTextView;

    protected FrameLayout titleLayout;

    protected ImageView titleLeftView;

    protected ImageView titleRightView;

    protected TextView titleRightText;

    protected TextView tipsMessageView;

    protected TextView cancelTipsTextView;

    public File cameraPhoto;

    public File cameraVideo;

    protected TextView badgeTextView;

    protected ImageView badgeView;

    protected RelativeLayout badgeLayout;

    private LinearLayout rootLayout;

    protected SwipeRefreshLayout refreshLayout;

    protected ListView chatListView;

    private TextView deleteTextView;

    private TextView typingTextView;

    private RelativeLayout banner;

    private ImageView bannerCloseImg;

    protected JXChatPresenter chatPresenter;

    private InputMethodManager inputMethodManager;

    protected JXChatAdapter chatAdapter;

    protected JXConversation conversation;

    private String subOrgId;

    private ChatType chatType;

    protected int type;

    private JXChatFragmentListener chatFragmentListener = null;

    private List<Drawable> functionImages = new ArrayList<Drawable>();

    private List<Integer> functionDrawRes ;

    private List<String> functionNames = new ArrayList<String>();

    private JXMessage sessionTipsMessage;

    private JXMessage cancelWaitMessage;

    private ListView inputAssociationListview;

    private JXInputAssociationAdapter inputAssociationAdapter;

    private String inputText;

    public boolean isChatWithRobot = false;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mContext = context;
        Bundle bundle = getArguments();
        String skillsId = bundle.getString(JXConstants.EXTRA_CHAT_KEY);
        type = bundle.getInt(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_CUSTOMER_SERVICE);
        if(type == JXChatView.CHATTYPE_MESSAGE_BOX){
            chatPresenter = new JXChatMsgBoxPresenter(this);
            return;
        }
        subOrgId = JXUiHelper.getInstance().getSuborgId();
        type = getChatType();
        if(type == CHATTYPE_CAHTROOM){
            chatType =  ChatType.CHATROOM;
        }else if(type == CHATTYPE_GROUPCHAT){
            chatType =  ChatType.GROUP_CHAT;
        }else if(type == CHATTYPE_SINGLECHAT){
            chatType =  ChatType.SINGLE_CHAT;
        }else if(type == CHATTYPE_CUSTOMER_SERVICE){
            chatType =  ChatType.CUSTOMER_SERVICE;
        }else {
            chatType =  ChatType.CUSTOMER_SERVICE;
        }
        chatPresenter = new JXChatPresenterImp(this, subOrgId, chatType,skillsId,mContext);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    }

    public void setJXChatFragmentListener(JXChatFragmentListener chatFragmentListener) {
        this.chatFragmentListener = chatFragmentListener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View chatView = inflater.inflate(R.layout.jx_fragment_chat, container, false);
        rootLayout = (LinearLayout)chatView.findViewById(R.id.ll_root);
        refreshLayout = (SwipeRefreshLayout)chatView.findViewById(R.id.refresh);
        refreshLayout.setColorSchemeResources(R.color.jx_orange500);
        refreshLayout.setOnRefreshListener(this);
        chatListView = (ListView)chatView.findViewById(R.id.messages_view);
        menuLayout = (JXInputMenuLayout)chatView.findViewById(R.id.inputlayout);
        voiceHintView = (JXVoiceHintView)chatView.findViewById(R.id.voice_hint_view);
        titleTextView = (TextView)chatView.findViewById(R.id.tv_title);
        deleteTextView = (TextView)chatView.findViewById(R.id.tv_del);
        titleLayout = (FrameLayout)chatView.findViewById(R.id.fl_title);
        titleLeftView = (ImageView)chatView.findViewById(R.id.iv_left);
        titleRightView = (ImageView)chatView.findViewById(R.id.iv_right);
        titleRightText = (TextView)chatView.findViewById(R.id.tv_right);
        badgeView = (ImageView) chatView.findViewById(R.id.iv_badge);
        badgeTextView = (TextView)chatView.findViewById(R.id.tv_badge);
        badgeLayout = (RelativeLayout)chatView.findViewById(R.id.rl_badge);
        tipsMessageView = (TextView)chatView.findViewById(R.id.tv_wait_tips);
        cancelTipsTextView = (TextView) chatView.findViewById(R.id.tv_cancel_tips);
        typingTextView = (TextView)chatView.findViewById(R.id.tv_type_state);
        inputAssociationListview = (ListView) chatView.findViewById(R.id.lv_input_association);
        banner = chatView.findViewById(R.id.rl_banner);
        bannerCloseImg = chatView.findViewById(R.id.iv_banner_close);
        badgeView.setOnClickListener(this);
        titleRightText.setOnClickListener(this);
        titleLeftView.setOnClickListener(this);
        deleteTextView.setOnClickListener(this);
        menuLayout.sendMsgView.setOnClickListener(this);
        menuLayout.voicePressButton.setOnClickListener(this);
        chatListView.setOnTouchListener(this);
        menuLayout.contentText.setOnTouchListener(this);
        menuLayout.funcPanelView.setOnItemClickListener(this);
        bannerCloseImg.setOnClickListener(this);
        inputMethodManager = (InputMethodManager)mContext
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if(type != CHATTYPE_MESSAGE_BOX){
            conversation = JXImManager.Conversation.getInstance().getConversation(subOrgId,chatType);

            if(functionImages != null && functionNames != null){
                menuLayout.configureFuncPanel(functionImages, functionNames);
            }
            menuLayout.setJXInputLayoutListener(inputLayoutListener);
            // 设置改会话的消息为已读
            conversation.setAsRead();
            chatAdapter = new JXChatAdapter(mContext, new ArrayList<JXMessage>(), chatListView,
                    conversation);
            chatAdapter.setJXChatFragmentListener(chatFragmentListener);
            chatListView.setAdapter(chatAdapter);
            if (JXImManager.Config.getInstance().isGetMessageFromDb()) {
                chatAdapter.refreshMessageList(conversation.getMessageList());
            }else {
                chatPresenter.fetchMessages(false, null, chatType);
            }
            if (!JXImManager.McsUser.getInstance().isCustomerSendEmoticonEnable()) {
                menuLayout.expressionImageView.setVisibility(View.GONE);
            }
            //坐席输入状态监听
            JXImManager.McsUser.getInstance().setChatStateListener(chatStateListener);
            //输入联想 和 输入状态监听
            menuLayout.contentText.addTextChangedListener(new InputTextListener());
            //输入联想
            if (JXUiHelper.getInstance().robotInputAssociateEnable() &&JXImManager.Config.getInstance().robotQuestionCompleteEnable()){
                inputAssociationListview.setOnItemClickListener(new InputAssociationItemClickListener());
                inputAssociationAdapter = new JXInputAssociationAdapter(mContext,new ArrayList<String>());
                inputAssociationListview.setAdapter(inputAssociationAdapter);
            }
            if (JXImManager.Config.getInstance().robotSatisfyEnable()){
                banner.setVisibility(View.VISIBLE);
            }
            //排队退出 留言 提示语处理
            handleWaitTipsOption();

        }else{
            chatAdapter = new JXChatAdapter(mContext, new ArrayList<JXMessage>(), chatListView,
                    conversation);
            chatListView.setStackFromBottom(false);
            chatListView.setAdapter(chatAdapter);
        }
        Bundle bundle = getArguments();
        String skillsId = bundle.getString(JXConstants.EXTRA_CHAT_KEY);
        String extendData = bundle.getString(JXConstants.EXTRA_CHAT_EXTEND_DATE);
        if(!TextUtils.isEmpty(skillsId)){
            requestCustomer(skillsId, extendData, JXUiHelper.TAG_NOT_TRANSFER,null, this);
        }
        configureView();
        return chatView;
    }

    @Override
    public void onResume() {
        super.onResume();
        isVisiable = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        isVisiable = false;
        // 聊天界面关闭时，将当前的聊天界面的消息置为已读
        if (conversation != null) {
            conversation.setAsRead();
            JXUiHelper.getInstance().notifyConversationListChange();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_PREVW_CODE) {
            return;
        }
        if (requestCode == GET_IMAGE_VIA_CAMERA && resultCode == Activity.RESULT_OK ) {
            if (cameraPhoto!=null&&cameraPhoto.exists()) {
                String path = cameraPhoto.getAbsolutePath();
                chatPresenter.sendImageMessage(path);
            }
        }else if (resultCode == Activity.RESULT_OK && null != data) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    Uri selectedImage = data.getData();
                    if (selectedImage == null) {
                        return;
                    }
                    String path = JXCommonUtils.getRealFilePath(mContext, selectedImage);
                    chatPresenter.sendImageMessage(path);
                    break;
                case VIDEO_REQUEST_CODE:
                    Uri selectedVideo = data.getData();
                    if (selectedVideo == null) {
                        return;
                    }
                    String videoPath = JXCommonUtils.getRealFilePath(mContext, selectedVideo);
                    chatPresenter.sendVideoMessage(videoPath);
                    break;
                case GET_VIDEO_VIA_CAMERA:
                    String camVideoPath=data.getStringExtra("localPath");
                    if (camVideoPath == null) {
                        JXLog.e("cannot get video uri");
                        return;
                    }
                    chatPresenter.sendVideoMessage(camVideoPath);
                    break;
                case LOCATION_REQUEST_CODE:
                    String lat = data.getStringExtra("lat");
                    String log = data.getStringExtra("log");
                    String lable = data.getStringExtra("lable");
                    JXLog.d("[JXBaseChatFragment.onActivityResult] lat = "+lat + " , log = "+log+" , lable = "+lable);
                    if (!TextUtils.isEmpty(lat) && !TextUtils.isEmpty(log) && !TextUtils.isEmpty(lable)){
                        chatPresenter.sendLocationMsg(lable,lat,log,JXChatView.DEFAULT_LOCATION_IMAGE_64);
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (chatType == ChatType.CUSTOMER_SERVICE && sessionTipsMessage != null) {
            conversation.removeMessage(sessionTipsMessage.getMessageId());
        }
        if (chatType == ChatType.CUSTOMER_SERVICE && cancelWaitMessage != null) {
            conversation.removeMessage(cancelWaitMessage.getMessageId());
        }
        refreshChatView(false, INVAILD_SELECTION);
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (JXVoicePlayListener.currentPlayListener!=null&&JXVoicePlayListener.isPlaying) {
            JXVoicePlayListener.currentPlayListener.stopPlayVoice();
        }
        chatPresenter.sendChatStateMessage(JXChatStateExtension.JXChatState.gone,"");
        menuLayout.onDestory();
        chatPresenter.onDestroy();
        if (chatAdapter != null) {
            chatAdapter.resetResource();
        }
        if(evaluateTask != null){
            evaluateTask.cancel(true);
        }
        JXImManager.McsUser.getInstance().setChatStateListener(null);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        this.mContext = null;
        isVisiable = false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.textSendButton) {
            chatPresenter.sendTextMessage(menuLayout.contentText.getText().toString());
            menuLayout.contentText.setText("");
        } else if (v.getId() == R.id.iv_left) {
            if (mContext != null) {
                getActivity().onBackPressed();
            }
        } else if (v.getId() == R.id.tv_del) {
            onMessageDeleteClick();
        } else if (v.getId() == R.id.iv_right) {
            onTitleRightViewClick();
        } else if(v.getId() == R.id.tv_right){
            onTitleRightTextClck();
        } else if (v.getId() == R.id.btn_close_evaluate) {
            if (evaluateWindow!=null&&evaluateWindow.isShowing()) {
                evaluateWindow.dismiss();
            }
            if (quickQuestionWindow!=null&&quickQuestionWindow.isShowing()) {
                quickQuestionWindow.dismiss();
            }
        } else if(v.getId() == R.id.btn_common_pop_window_close){
            if (commonQuestionWindow!=null&&commonQuestionWindow.isShowing()) {
                commonQuestionWindow.dismiss();
            }
        } else if(v.getId() == R.id.iv_banner_close){
            banner.setVisibility(View.GONE);
        }else {
            processOnclick(v);
        }
    }

    /**
     * 是否处于音频录制中
     */
    protected boolean isVoiceRecording = false;
    @Override
    public boolean onMessageItemClick(final JXMessage jxMessage) {
        if(jxMessage instanceof RichTextMessage){
            RichTextMessage richTextMessage = (RichTextMessage)jxMessage;
            chatPresenter.sendTextMessage(richTextMessage.getUrl());
            return true;
        }else if(jxMessage.getType() == JXMessage.Type.EVALUATION){
            chatPresenter.fetchEvaluateInfo(jxMessage,false);
            return true;
        }else if(jxMessage.getType() == JXMessage.Type.VOICE && isVoiceRecording){
            return true;
        }else if (jxMessage.getType() == JXMessage.Type.IMAGE){
            ImageMessage imageMessage = (ImageMessage) jxMessage;
            startActivity(new Intent(getContext(),JXPhotoActivity.class)
                    .putExtra("MessageID", imageMessage.getMessageId())
                    .putExtra("LocalUrl", imageMessage.getLocalUrl())
                    .putExtra("Direction", imageMessage.getDirect().toString()));
            getActivity().overridePendingTransition(android.R.anim.fade_in,0);
        } else if (jxMessage.getType() == JXMessage.Type.TEXT && jxMessage.getAttributes().get
                (JXMessageAttribute.AMAP_URL.value()) != null) {
            String amapUrl = jxMessage.getStringAttribute(JXMessageAttribute.AMAP_URL.value(), "");
            startActivity(new Intent(getActivity(), JXWebViewActivity.class).putExtra(JXConstants
                    .EXTRA_WEBVIEW_URL, amapUrl).putExtra(JXConstants.EXTRA_AMAP_URL, true));
        } else if (jxMessage.getType() == JXMessage.Type.LOCATION){
            //位置消息
            LocationMessage locationMessage = (LocationMessage) jxMessage;
            double longitude = locationMessage.getLongitude();
            double latitude = locationMessage.getLatitude();
            String position = String.valueOf(longitude)+","+String.valueOf(latitude);
            String url = String.format(amapLoactionUrl,position,locationMessage.getLabel());
            startActivity(new Intent(getActivity(), JXWebViewActivity.class).putExtra(JXConstants
                    .EXTRA_WEBVIEW_URL, url).putExtra(JXConstants.EXTRA_AMAP_URL, true));
        }
        return false;
    }

    protected abstract void onMessageDeleteClick();
    protected abstract void onTitleRightViewClick();
    protected abstract void onTitleRightTextClck();
    protected abstract void onTitleLeftViewClick();
    protected abstract void processOnclick(View v);
    protected abstract void processWaitTipsOption(String action);

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (v.getId() == R.id.messages_view) {
                menuLayout.expressionLayout.setVisibility(View.GONE);
                menuLayout.funcPanelView.setVisibility(View.GONE);
                hiddenInput();
            } else if (v.getId() == R.id.textinput) {
                menuLayout.funcPanelView.setVisibility(View.GONE);
                menuLayout.expressionLayout.setVisibility(View.GONE);
                chatListView.setSelection(chatListView.getBottom());
            }
        }
        return false;
    }

    @Override
    public void onRefresh() {
        if (chatAdapter == null) {
            refreshLayout.setRefreshing(false);
            return;
        }
        if (chatAdapter != null && chatAdapter.getCount() == 0) {
            refreshLayout.setRefreshing(false);
            return;
        }
        if (JXImManager.Config.getInstance().isGetMessageFromDb()) {
            JXMessage jxMessage = (JXMessage)chatAdapter.getItem(0);
            chatPresenter.loadMoreMessages(jxMessage.getMessageId());
        }else {
            if (chatType == ChatType.CUSTOMER_SERVICE){
                if (conversation != null){
                    List<JXMessage> jxMessages = conversation.getMessageList();
                    chatPresenter.fetchMessages(true, jxMessages.size() != 0 ? jxMessages.get(0) : null, chatType);
                }
            }else {
                chatPresenter.loadMoreMessages(null);
            }
        }
    }

    @Override
    public abstract void showProgress(int requestTag);

    @Override
    public abstract void hideProgress();

    @Override
    public void showFunctionPanel() {
        menuLayout.funcPanelView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideFunctionPanel() {
        menuLayout.funcPanelView.setVisibility(View.GONE);
    }

    @Override
    public boolean isVisiable() {
        return isVisiable;
    }

    @Override
    public void refreshChatView(final boolean isSelectBottom, final int selection) {
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                if (chatListView != null && chatAdapter != null && conversation != null) {
                    chatAdapter.refreshMessageList(conversation.getMessageList());
                    if (isSelectBottom) {
                        chatListView.setSelection(chatListView.getBottom());
                    } else {
                        if (selection != JXChatView.INVAILD_SELECTION) {
                            chatListView.setSelection(selection);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onItemClick(android.widget.AdapterView<?> parent, View view, int position,
            long id) {
        menuLayout.funcPanelView.setVisibility(View.GONE);
        onFunctionItemClick(position, functionDrawRes.get(position));
    };

    @Override
    public void interruptRefresh() {
        if(mHandler != null){
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if(refreshLayout != null){
                        refreshLayout.setRefreshing(false);
                    }
                }
            });
        }
    }

    @Override
    public void showDeleteMessageSuccess(boolean isMultiDel) {
    }

    /**
     * 功能面板点击事件
     *
     * @param position
     * @param drawableResId
     */
    public abstract void onFunctionItemClick(int position, int drawableResId);

    /**
     * 隐藏输入法
     *
     * @param event
     */
    public void hiddenInput() {
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText.getWindowToken(), 0);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (menuLayout.onBackEvent()) {
            return true;
        }
        if (chatAdapter != null && chatAdapter.isDelMode()) {
            chatAdapter.setDelChoiceMode(false);
            menuLayout.setVisibility(View.VISIBLE);
            deleteTextView.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    /**
     * 消息重发
     *
     * @param jxMessage
     */
    protected void resendMessage(JXMessage jxMessage) {
        chatPresenter.resendMessage(jxMessage);
    }

    /**
     * 复制文本消息
     *
     * @param message
     */
    protected void copyTextMessage(TextMessage message) {
        chatPresenter.copyTextMessage(message.getContent());
    }

    /**
     * 删除消息
     *
     * @param jxMessage
     */
    protected void deleteMessage(JXMessage jxMessage) {
        chatPresenter.deleteMessage(jxMessage);
    }

    /**
     * 设置是否为删除模式
     *
     * @param isDelChoiceMode
     */
    protected void setDelChoiceMode(boolean isDelChoiceMode) {
        if (isDelChoiceMode) {
            deleteTextView.setVisibility(View.VISIBLE);
            chatAdapter.setDelChoiceMode(true);
            menuLayout.setVisibility(View.GONE);
        } else {
            deleteTextView.setVisibility(View.GONE);
            chatAdapter.setDelChoiceMode(false);
            menuLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 客服请求
     *
     * @param skillsId
     * @param Tag
     */
    protected void requestCustomer(String skillsId, String extendData, int Tag, JXMessage triggerMsg, RequestCusServiceCallback callback) {
        chatPresenter.requestCustomer(skillsId, extendData, Tag,triggerMsg , callback);
    }

    /**
     * 自定义配置控件
     * 若开发者需要重新定义控件的背景、大小等时，可override此方法
     */
    protected void configureView(){
        if (JXUiHelper.getInstance().getChatBgdrawableResId() != JXUiHelper.INVALID_INT) {
            setChatBackground(JXUiHelper.getInstance().getChatBgdrawableResId());
        }
        if (JXUiHelper.getInstance().getExpressionPanelHeight() != JXUiHelper.INVALID_INT) {
            menuLayout
                    .setExpressionPanelHeight(JXUiHelper.getInstance().getExpressionPanelHeight());
        }
        if (JXUiHelper.getInstance().getFunctionPanelHeight() != JXUiHelper.INVALID_INT) {
            menuLayout.setFunctionPanelHeight(JXUiHelper.getInstance().getFunctionPanelHeight());
        }
        if (JXUiHelper.getInstance().getmTitleHeight() != JXUiHelper.INVALID_INT) {
            setTitleHeight(JXUiHelper.getInstance().getmTitleHeight());
        }
        if (JXUiHelper.getInstance().getInputMenuHeight() != JXUiHelper.INVALID_INT) {
            menuLayout.setInputMenuHeight(JXUiHelper.getInstance().getInputMenuHeight());
        }
        if (JXUiHelper.getInstance().getmTitleBgColorId() != JXUiHelper.INVALID_INT) {
            titleLayout.setBackgroundColor(getResources().getColor(JXUiHelper.getInstance().getmTitleBgColorId()));
        }
        if (JXUiHelper.getInstance().getmTitleLeftImgResId() != JXUiHelper.INVALID_INT) {
            titleLeftView.setImageResource(JXUiHelper.getInstance().getmTitleLeftImgResId());
        }
        if (JXUiHelper.getInstance().getmTitleTextColorResId() != JXUiHelper.INVALID_INT) {
            titleTextView.setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
            titleRightText.setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
        }
    }

    /**
     * 设置标题高度
     * @param height
     */
    protected void setTitleHeight(int height){
        if(height < 0){
            return;
        }
        ViewGroup.LayoutParams titleParams = titleLayout.getLayoutParams();
        titleParams.height = height;
        titleLayout.setLayoutParams(titleParams);
    }

    /**
     * 设置消息Item的背景
     * @param type 消息类型
     * @param resId 消息Item的资源ID
     */
    public void setMessageItemBgDrawable(JXMessage.Type type, JXMessage.Direction direction, @AnyRes int resId){
        if(chatAdapter != null){
            chatAdapter.setMessageItemBgDrawable(type, direction, resId);
        }
    }

    /**
     * @return
     * @see
     * <ul>
     * <li>{@link JXChatView#CHATTYPE_CAHTROOM}</li>
     * <li>{@link JXChatView#CHATTYPE_CUSTOMER_SERVICE}</li>
     * <li>{@link JXChatView#CHATTYPE_GROUPCHAT}</li>
     * <li>{@link JXChatView#CHATTYPE_SINGLECHAT}</li>
     * </ul>
     */
    protected abstract int getChatType();

    protected void setChatBackground(@DrawableRes int drawableResId){
        if(chatListView != null){
            chatListView.setBackgroundResource(drawableResId);
        }
    }

    @SuppressWarnings("deprecation")
    protected void setChatBackground(Drawable backgroundDrawable){
        if(chatListView != null){
            chatListView.setBackgroundDrawable(backgroundDrawable);
        }
    }

    /**
     * 处理批量删除
     */
    protected void handleMultiMessageDel(){
        SparseBooleanArray booleanArray = chatListView.getCheckedItemPositions();
        List<String>messageIdList = new ArrayList<>();
        for (int i = 0; i < booleanArray.size(); i++) {
            if (booleanArray.valueAt(i)) {
                int  position = booleanArray.keyAt(i);
                messageIdList.add(chatAdapter.list.get(position).getMessageId());
            }
        }
        if(!messageIdList.isEmpty()){
            conversation.removeMessage(messageIdList);
            if(chatAdapter != null){
                chatAdapter.removeImageTagCache(messageIdList);
            }
            refreshChatView(false, INVAILD_SELECTION);
            setDelChoiceMode(false);
            showDeleteMessageSuccess(true);
        }else{
            showDeleteMessageSuccess(false);
        }
    }

    /**
     * 设置功能面板
     * @param functionDrawRes 功能面板资源数组
     * @param functionNames 功能面板对应的名称
     */
    public void configFunctionPanel(List<Integer> functionDrawRes, List<String> functionNames){
        if(mContext == null){
            return;
        }
        if(functionDrawRes != null){
            this.functionDrawRes = functionDrawRes;
            this.functionImages.clear();
            for (int i = 0; i < functionDrawRes.size(); i++) {
                this.functionImages.add(mContext.getResources().getDrawable(functionDrawRes.get(i)));
            }
        }
        if(this.functionImages != null && functionNames != null){
            this.functionNames.clear();
            this.functionNames.addAll(functionNames);
            menuLayout.configureFuncPanel(this.functionImages, this.functionNames);
        }
    }

    public PopupWindow evaluateWindow;
    ListView evaluateView;
    JXEvaluateAdapter mJXEvaluateAdapter;
    List<Option> evaluateList = new ArrayList<Option>();
    Button closeButton ;
    TextView titleView;
    View evaluateHeaderView;
    JXMessage evaluateMessage;
    JXSatisfication satisfication;
    boolean isCloseSession;
    /**
     * 显示满意度评价的窗口
     * @param message
     */
    @SuppressLint("InflateParams")
    @Override
    public void showEvaluateWindow(JXSatisfication satisfication ,JXMessage evaluateMessage, boolean isCloseSession) {
        if (conversation.getSessionStatus() == SessionStatus.Waiting) {
            JXCommonUtils.showToast(mContext, getString(R.string.jx_cannot_evaluate_in_waiting));
            return;
        }
        this.evaluateMessage = evaluateMessage;
        this.isCloseSession = isCloseSession;
        this.satisfication = satisfication;
        if (mContext == null) {
            return;
        }
        if (satisfication != null && satisfication.getOptions() != null) {
            if (evaluateView == null) {
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                evaluateView = (ListView) inflater.inflate(R.layout.jx_evaluate_pop_window,
                        null);
                evaluateHeaderView = inflater.inflate(R.layout.jx_evaluate_item_header, null);
                evaluateView.addHeaderView(evaluateHeaderView);
                titleView = (TextView) evaluateHeaderView.findViewById(R.id.tv_title);
                titleView.setText(getString(R.string.jx_invite_evaluate));
                closeButton = (Button) evaluateHeaderView
                        .findViewById(R.id.btn_close_evaluate);
                closeButton.setOnClickListener(JXBaseChatFragment.this);
            }
            // 创建PopupWindow对象
            if (evaluateWindow == null) {
                evaluateWindow = new PopupWindow(evaluateView, LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT, false);
                evaluateList.addAll(satisfication.getOptions());
                mJXEvaluateAdapter = new JXEvaluateAdapter(mContext, evaluateList,
                        satisfication);
                mJXEvaluateAdapter.setJXChatFragmentListener(JXBaseChatFragment.this);
                evaluateView.setAdapter(mJXEvaluateAdapter);
                evaluateView.setOnItemClickListener(evaluateItemClickListener);
                evaluateWindow.setBackgroundDrawable(new ColorDrawable(0));
                // 设置点击窗口外边窗口消失
                evaluateWindow.setOutsideTouchable(true);
                evaluateWindow.setFocusable(true);
                evaluateWindow.setAnimationStyle(R.style.JXAnimationPreview);
            }
            evaluateWindow.showAtLocation(rootLayout,
                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText.getWindowToken
                        (), 0);
            }
        } else {
            JXCommonUtils.showToast(mContext, "get satisfication failed!");
        }
    }

    /**
     * 设置popupWindow显示和关闭时window背景的透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        if(mContext == null){
            return;
        }
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    private JXEvaluateTask evaluateTask = null;

    @Override
    public void onEvaluateItemClick(int value) {
        if(evaluateWindow != null){
            evaluateWindow.dismiss();
            evaluateTask = new JXEvaluateTask(conversation, evaluateMessage ,  value );
            evaluateTask.setJXEvaluteTaskCallback(callback);
            evaluateTask.execute();
        }
    }

    /**
     * 评价item监听器
     */
    OnItemClickListener evaluateItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (satisfication.getSatisficationType() != 3) {
                final Option option = (Option) mJXEvaluateAdapter.getItem(position - 1);
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setMessage(R.string.jx_submit_evaluation);
                builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        onEvaluateItemClick(option.getValue());
                    }
                });
                builder.setNegativeButton(android.R.string.no, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
                builder.create().show();
            }
        }
    };

    private JXEvaluteTaskCallback callback = new JXEvaluteTaskCallback() {

        public void onEvalutePre() {
            showProgress(JXUiHelper.TAG_EVALUTE);
        };

        @Override
        public void onEvaluteSuccess() {
            if (mContext == null || !isAdded()) {
                return;
            }
            hideProgress();
            if (evaluateMessage != null) {
                evaluateMessage.setEvaluated();
                conversation.setEvaluated(false);
            }
            if (satisfication.isShowThanksMeg()) {
                chatPresenter.saveEvaluateFeedbackMessage(satisfication.getThanksMsg());
            }
            if (isCloseSession) {
                requestCustomer(conversation.getSkillsId(),null, JXUiHelper.TAG_CLOSE_SESSION,null, JXBaseChatFragment.this);
            }
        }

        @Override
        public void onEvaluetError(int errorCode) {
            if (mContext == null || !isAdded()) {
                return;
            }
            hideProgress();
            if (isAdded()){
                if (errorCode == JXEvaluateTask.EVALUATE_TIMEOUT) {
                    JXCommonUtils.showToast(mContext, getString(R.string.jx_submit_evaluation_timeout));
                }else {
                    JXCommonUtils.showToast(mContext, getString(R.string.jx_submit_evaluation_failed));
                }
                if (isCloseSession) {
                    requestCustomer(conversation.getSkillsId(),null, JXUiHelper.TAG_CLOSE_SESSION,null, JXBaseChatFragment.this);
                }
            }
        }
    };

    private PopupWindow quickQuestionWindow;
    private ListView quickQuestionListView;
    private TextView questionTitle;
    private Button questionCloseBtn;
    private View quickQuestionHeaderView;
    private JXQuickQuestionAdapter questionAdapter;
    /**显示快捷提问窗口**/
    @Override
    public void showQuickQuestionWindows(List<String> questionlist){
        if(mContext == null){
            return;
        }
        if (questionlist == null) {
            JXCommonUtils.showToast(mContext, getString(R.string.jx_quick_question_exception));
            return;
        }
        if (questionlist.size()==0) {
            JXCommonUtils.showToast(mContext, getString(R.string.jx_quick_question_is_null));
        }else{
            if (quickQuestionListView == null) {
                LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                quickQuestionListView = (ListView)inflater.inflate(R.layout.jx_evaluate_pop_window,
                        null);
                quickQuestionHeaderView = inflater.inflate(R.layout.jx_evaluate_item_header, null);
                quickQuestionListView.addHeaderView(quickQuestionHeaderView);
                questionTitle = (TextView)quickQuestionHeaderView.findViewById(R.id.tv_title);
                questionTitle.setText(getString(R.string.jx_commonly_used_quick_questions));
                questionCloseBtn = (Button)quickQuestionHeaderView
                        .findViewById(R.id.btn_close_evaluate);
                questionCloseBtn.setOnClickListener(JXBaseChatFragment.this);
            }
            // 创建PopupWindow对象
            if (quickQuestionWindow == null) {
                questionAdapter = new JXQuickQuestionAdapter(mContext, questionlist);
                quickQuestionListView.setAdapter(questionAdapter);
                quickQuestionListView.setOnItemClickListener(quickQuestionItemListener);
                quickQuestionWindow = new PopupWindow(quickQuestionListView, LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT, false);
                quickQuestionWindow.setBackgroundDrawable(new ColorDrawable(0));
                // 设置点击窗口外边窗口消失
                quickQuestionWindow.setOutsideTouchable(true);
                quickQuestionWindow.setFocusable(true);
                quickQuestionWindow.setAnimationStyle(R.style.JXAnimationPreview);
            }
            quickQuestionWindow.showAtLocation(rootLayout,
                    Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText.getWindowToken(), 0);
            }
        }
    }

    OnItemClickListener quickQuestionItemListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String question = (String)questionAdapter.getItem(position-1);
            menuLayout.contentText.setText(question);
            menuLayout.contentText.setSelection(question.length());
            if (quickQuestionWindow!=null&&quickQuestionWindow.isShowing()) {
                quickQuestionWindow.dismiss();
            }
        }
    };

    protected synchronized void saveTmpSessionMsg(String tipsMessage, String skillsId){
        if(chatType == ChatType.CUSTOMER_SERVICE && sessionTipsMessage == null){
            sessionTipsMessage = JXUiHelper.getInstance().saveSessionMsg(tipsMessage, subOrgId, null);
        }
        if(chatType == ChatType.CUSTOMER_SERVICE && sessionTipsMessage != null){
            conversation.removeMessage(sessionTipsMessage.getMessageId());
            TextMessage message = (TextMessage)sessionTipsMessage;
            message.setContent(tipsMessage);
            conversation.addMessage(sessionTipsMessage);
            refreshChatView(false, INVAILD_SELECTION);
        }
    }


    JXInputLayoutListener inputLayoutListener = new JXInputLayoutListener() {

        @Override
        public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
            isVoiceRecording = true;
            return voiceHintView.pressToSpeak(v, event, new voiceRecorderCallBack() {

                @Override
                public void recordSuccess(String recordingPath, int recordDur) {
                    isVoiceRecording = false;
                    chatPresenter.sendVoiceMessage(recordingPath, recordDur);
                }
                public void recordAbandon() {
                    isVoiceRecording = false;
                };
            });
        }
    };

    public void deleteSessionTipsMsg(boolean isDelNormalTips, boolean isDelCancelWait){
        if(chatType == ChatType.CUSTOMER_SERVICE && sessionTipsMessage!= null
                && isDelNormalTips){
            conversation.removeMessage(sessionTipsMessage.getMessageId());
            refreshChatView(false, INVAILD_SELECTION);
        }
        if (chatType == ChatType.CUSTOMER_SERVICE && cancelWaitMessage != null
                && isDelCancelWait) {
            conversation.removeMessage(cancelWaitMessage.getMessageId());
        }
    }

    class InputAssociationItemClickListener implements OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            String associationText = (String) adapterView.getItemAtPosition(position);
            menuLayout.contentText.setText(associationText);
            menuLayout.contentText.setSelection(associationText.length());
            inputAssociationListview.setVisibility(View.GONE);
            inputAssociationHandler.removeMessages(START_ASSOCIATION);
        }
    }


    class InputTextListener implements TextWatcher{

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            inputText = s.toString();
            if (TextUtils.isEmpty(inputText)) {
                if (menuLayout.sendMsgView.getVisibility() == View.VISIBLE) {
                    menuLayout.sendMsgView.setVisibility(View.INVISIBLE);
                    menuLayout.moreImageView.setVisibility(View.VISIBLE);
                }
            } else {
                if (menuLayout.sendMsgView.getVisibility() == View.INVISIBLE) {
                    menuLayout.sendMsgView.setVisibility(View.VISIBLE);
                    menuLayout.moreImageView.setVisibility(View.INVISIBLE);
                }
            }
            if (isChatWithRobot){
                //机器人输入联想
                if (JXUiHelper.getInstance().robotInputAssociateEnable()&&JXImManager.Config.getInstance().robotQuestionCompleteEnable()){
                    if (TextUtils.isEmpty(inputText)) {
                        inputAssociationListview.setVisibility(View.GONE);
                        inputAssociationHandler.removeMessages(START_ASSOCIATION);
                        inputAssociationHandler.sendEmptyMessage(STOP_ASSOCIATION);
                    } else {
                        inputAssociationHandler.removeMessages(START_ASSOCIATION);
                        inputAssociationHandler.sendEmptyMessageDelayed(START_ASSOCIATION,1000);
                    }
                }
            }else {
                //输入状态发送
                if (JXImManager.McsUser.getInstance().isPrepareMsgFlagOpen()) {
                    if (TextUtils.isEmpty(inputText)) {
                        sendStateMsgHandler.removeMessages(COMPOSING_STATE);
                        sendStateMsgHandler.sendEmptyMessage(STOP_STATE);
                    } else {
                        sendStateMsgHandler.sendEmptyMessageDelayed(COMPOSING_STATE, 1000);
                    }
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    Handler inputAssociationHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case START_ASSOCIATION:
                    chatPresenter.getInputAssociationList(inputText);
                    break;
                case STOP_ASSOCIATION:
                    break;
                default:
                    break;
            }
        };
    };

    public Handler sendStateMsgHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case COMPOSING_STATE:
                    chatPresenter.sendChatStateMessage(JXChatStateExtension.JXChatState.composing,inputText);
                    break;
                case VOICE_RECORDING_STATE:
                    break;
                case STOP_STATE:
                    chatPresenter.sendChatStateMessage(JXChatStateExtension.JXChatState.gone,"");
                    break;
                default:
                    break;
            }
        };
    };

    @Override
    public void removeComposingStateMsg() {
        sendStateMsgHandler.removeMessages(COMPOSING_STATE);
    }

    @Override
    public void refreshInputAssociationList(final List<String> associationList) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(inputText)){
                    return;
                }
                inputAssociationAdapter.refreshMessageList(associationList);
                inputAssociationListview.setVisibility(View.VISIBLE);
                inputAssociationListview.bringToFront();
            }
        });
    }


    JXChatStateListener chatStateListener = new JXChatStateListener() {
        @Override
        public void onTextChange(final String text, String sessionId) {
            if (sessionId!=null && sessionId.equals(conversation.getSessionId())){
                cleanTypeStateMsgHandler.removeMessages(0);
                cleanTypeStateMsgHandler.sendEmptyMessageDelayed(0, 5000);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        typingTextView.setVisibility(View.VISIBLE);
                    }
                });
            }
        }

        @Override
        public void onRecording(String sessionId) {

        }

        @Override
        public void onStop(String sessionId) {
            if (sessionId!=null && sessionId.equals(conversation.getSessionId())){
                cleanTypeStateMsgHandler.removeMessages(0);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        typingTextView.setVisibility(View.GONE);
                    }
                });
            }
        }
    };

    Handler cleanTypeStateMsgHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            typingTextView.setVisibility(View.GONE);
        };
    };

    /**
     * 订单弹窗
     */
    private PopupWindow orderWindow;
    private RelativeLayout orderLayout;
    private ListView orderListView;
    private TextView orderWindowTitle;
    private ImageView orderCloseBtn;
    private View orderHeaderView;
    private JXOrderListAdapter orderListAdapter;
    private SwipeRefreshLayout orderSwipeRefreshLayout;
    public View orderLoadingView;
    public List<JXOrderInfo> orderList = new ArrayList<JXOrderInfo>();
    public boolean isOrderListNeedRefresh = true;
    private boolean hasMoreOrderList = false;
    boolean isOrderListLoading = false;

    /**显示订单窗口**/
    public void showOrderListWindows(){
        if (mContext == null) {
            return;
        }
        if (orderLayout == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            orderLayout = (RelativeLayout) inflater.inflate(R.layout.jx_common_pop_window,
                    null);
            orderSwipeRefreshLayout = (SwipeRefreshLayout) orderLayout.findViewById(R.id.common_pop_window_refresh);
            orderListView = (ListView) orderLayout.findViewById(R.id.lv_common_pop_window);
            orderWindowTitle = (TextView) orderLayout.findViewById(R.id.tv_common_pop_window_title);
            orderWindowTitle.setText(getString(R.string.jx_select_order));
            orderCloseBtn = (ImageView) orderLayout
                    .findViewById(R.id.btn_common_pop_window_close);
            orderCloseBtn.setOnClickListener(JXBaseChatFragment.this);
            orderSwipeRefreshLayout.setColorSchemeResources(R.color.jx_title_bar);
            orderSwipeRefreshLayout.setOnRefreshListener(orderRefreshListener);
            orderLoadingView = inflater.inflate(R.layout.jx_item_common_list_loadingview, null);
            orderListView.setOnScrollListener(scrollListener);
        }
        // 创建PopupWindow对象
        if (orderWindow == null) {
            orderListAdapter = new JXOrderListAdapter(mContext, new ArrayList<JXOrderInfo>());
            orderListView.setAdapter(orderListAdapter);
            orderListView.setOnItemClickListener(orderItemListener);
            orderWindow = new PopupWindow(orderLayout, LayoutParams
                    .MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT, false);
            orderWindow.setBackgroundDrawable(new ColorDrawable(0));
            // 设置点击窗口外边窗口消失
            orderWindow.setOutsideTouchable(true);
            orderWindow.setFocusable(true);
            orderWindow.setAnimationStyle(R.style.JXAnimationPreview);
            orderWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    orderSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }
        orderWindow.showAtLocation(rootLayout,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText
                    .getWindowToken(), 0);
        }
        orderSwipeRefreshLayout.post(new Runnable() {
            public void run() {
                orderSwipeRefreshLayout.setRefreshing(true);
            }
        });
        hasMoreOrderList = false;
        isOrderListLoading = true;
        if (orderListView.getFooterViewsCount()>0) {
            orderListView.removeFooterView(orderLoadingView);
        }
        orderListView.setSelection(0);
        orderRefreshListener.onRefresh();
    }

    @Override
    public void refreshOrderList(List<JXOrderInfo> refreshOrderList, boolean hasMore, boolean refresh){
        hasMoreOrderList = hasMore;
        isOrderListLoading = false;
        if (mContext !=null && orderWindow.isShowing()){
            if (orderListView.getFooterViewsCount()>0) {
                orderListView.removeFooterView(orderLoadingView);
            }
            if (refresh){
                //刷新
                orderSwipeRefreshLayout.setRefreshing(false);
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    orderList.clear();
                    orderList.addAll(refreshOrderList);
                    orderListAdapter.refresh(refreshOrderList);
                    orderListView.setSelection(0);
                }else {
                    orderWindow.dismiss();
                    JXCommonUtils.showToast(mContext,mContext.getString(R.string.jx_can_not_find_order));
                }
            }else {
                //加载更多
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    int w_cur_pos=orderListView.getFirstVisiblePosition();
                    this.orderList.addAll(refreshOrderList);
                    orderListAdapter.refresh(this.orderList);
                    orderListView.setAdapter(orderListAdapter);
                    orderListView.setSelection(w_cur_pos);
                }
            }
            if (hasMore){
                orderListView.addFooterView(orderLoadingView, null, false);
            }
        }
    }

    public AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // 当滚到最后一行且停止滚动时，执行加载
            if (view.getLastVisiblePosition() == view.getCount() - 1
                    && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                    && hasMoreOrderList && !isOrderListLoading) {
                isOrderListLoading = true;
                chatPresenter.fetchOrderList(false);

            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int
                totalItemCount) {

        }
    };

    public OnRefreshListener orderRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            chatPresenter.fetchOrderList(true);
        }
    };

    OnItemClickListener orderItemListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            JXOrderInfo orderInfo = (JXOrderInfo) orderListAdapter.getItem(position);
            chatPresenter.sendOrderMessage(orderInfo);
            if (orderWindow != null && orderWindow.isShowing()) {
                orderWindow.dismiss();
            }
        }
    };

    /**
     * 常见问题弹窗
     */
    private PopupWindow commonQuestionWindow;
    private RelativeLayout commonQuestionLayout;
    private ListView commonQuestionListView;
    private TextView commonQuestionWindowTitle;
    private ImageView commonQuestionCloseBtn;
    private View commonQuestionHeaderView;
    private JXCommonQuestionListAdapter commonQuestionListAdapter;
    private SwipeRefreshLayout commonQuestionSwipeRefreshLayout;
    public View commonQuestionLoadingView;
    List<JXCommonQuestion> commonQuestionList = new ArrayList<JXCommonQuestion>();
    public boolean isCommonQuestionListNeedRefresh = true;
    private boolean hasMoreCommonQuestionList = false;
    boolean isCommonQuestionListLoading = false;

    /**显示订单窗口**/
    public void showCommonQuestionListWindows(){
        if (mContext == null || !isAdded()) {
            return;
        }
        if (commonQuestionLayout == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            commonQuestionLayout = (RelativeLayout) inflater.inflate(R.layout.jx_common_pop_window,
                    null);
            commonQuestionSwipeRefreshLayout = (SwipeRefreshLayout) commonQuestionLayout.findViewById(R.id.common_pop_window_refresh);
            commonQuestionListView = (ListView) commonQuestionLayout.findViewById(R.id.lv_common_pop_window);
            commonQuestionWindowTitle = (TextView) commonQuestionLayout.findViewById(R.id.tv_common_pop_window_title);
            commonQuestionWindowTitle.setText(getString(R.string.jx_common_question));
            commonQuestionCloseBtn = (ImageView) commonQuestionLayout
                    .findViewById(R.id.btn_common_pop_window_close);
            commonQuestionCloseBtn.setOnClickListener(JXBaseChatFragment.this);
            commonQuestionSwipeRefreshLayout.setColorSchemeResources(R.color.jx_title_bar);
            commonQuestionSwipeRefreshLayout.setOnRefreshListener(commonQuestionRefreshListener);
            commonQuestionLoadingView = inflater.inflate(R.layout.jx_item_common_list_loadingview, null);
            commonQuestionListView.setOnScrollListener(commonQuestionsScrollListener);
        }
        // 创建PopupWindow对象
        if (commonQuestionWindow == null) {
            commonQuestionListAdapter = new JXCommonQuestionListAdapter(mContext, new ArrayList<JXCommonQuestion>(),chatPresenter);
            commonQuestionListView.setAdapter(commonQuestionListAdapter);
//            commonQuestionListView.setOnItemClickListener(commonQuestionItemListener);
            commonQuestionWindow = new PopupWindow(commonQuestionLayout, LayoutParams
                    .MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT, false);
            commonQuestionWindow.setBackgroundDrawable(new ColorDrawable(0));
            // 设置点击窗口外边窗口消失
            commonQuestionWindow.setOutsideTouchable(true);
            commonQuestionWindow.setFocusable(true);
            commonQuestionWindow.setAnimationStyle(R.style.JXAnimationPreview);
            commonQuestionWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    commonQuestionSwipeRefreshLayout.setRefreshing(false);
                    commonQuestionListAdapter.removeAllCache();
                }
            });
        }
        commonQuestionWindow.showAtLocation(rootLayout,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText
                    .getWindowToken(), 0);
        }
        hasMoreCommonQuestionList = false;
        isCommonQuestionListLoading = true;
        if (commonQuestionListView.getFooterViewsCount()>0) {
            commonQuestionListView.removeFooterView(commonQuestionLoadingView);
        }
        commonQuestionSwipeRefreshLayout.setRefreshing(true);
        commonQuestionListView.setSelection(0);
        commonQuestionRefreshListener.onRefresh();
    }

    @Override
    public void refreshCommonQuestionList(List<JXCommonQuestion> refreshCommonQuestionList, boolean hasMore, boolean refresh){
        if (mContext == null || !isAdded()) {
            return;
        }
        hasMoreCommonQuestionList = hasMore;
        isCommonQuestionListLoading = false;
        if (mContext !=null && commonQuestionWindow.isShowing()){
            if (commonQuestionListView.getFooterViewsCount()>0) {
                commonQuestionListView.removeFooterView(commonQuestionLoadingView);
            }
            if (refresh){
                //刷新
                commonQuestionSwipeRefreshLayout.setRefreshing(false);
                if (refreshCommonQuestionList != null && refreshCommonQuestionList.size()>0){
                    commonQuestionList.clear();
                    commonQuestionList.addAll(refreshCommonQuestionList);
                    commonQuestionListAdapter.refresh(refreshCommonQuestionList);
                    commonQuestionListView.setSelection(0);
                }else {
                    commonQuestionWindow.dismiss();
                    JXCommonUtils.showToast(mContext,mContext.getString(R.string.jx_can_not_find_common_question));
                }
                commonQuestionListAdapter.removeAllCache();
            }else {
                //加载更多
                if (refreshCommonQuestionList != null && refreshCommonQuestionList.size()>0){
                    int w_cur_pos=commonQuestionListView.getFirstVisiblePosition();
                    this.commonQuestionList.addAll(refreshCommonQuestionList);
                    commonQuestionListAdapter.refresh(this.commonQuestionList);
                    commonQuestionListView.setAdapter(commonQuestionListAdapter);
                    commonQuestionListView.setSelection(w_cur_pos);
                }
            }
            if (hasMore){
                commonQuestionListView.addFooterView(commonQuestionLoadingView, null, false);
            }
        }
    }

    public AbsListView.OnScrollListener commonQuestionsScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // 当滚到最后一行且停止滚动时，执行加载
            if (view.getLastVisiblePosition() == view.getCount() - 1
                    && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                    && hasMoreCommonQuestionList && !isCommonQuestionListLoading) {
                isCommonQuestionListLoading = true;
                chatPresenter.fetchcommonQuestionList(false);
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int
                totalItemCount) {

        }
    };

    public OnRefreshListener commonQuestionRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            chatPresenter.fetchcommonQuestionList(true);
        }
    };

    OnItemClickListener commonQuestionItemListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            JXCommonQuestion question = (JXCommonQuestion) commonQuestionListAdapter.getItem(position);
            commonQuestionListAdapter.switchQuestion(question.getId());
            commonQuestionListAdapter.notifyDataSetChanged();
        }
    };


    /**
     * 追一机器人订单弹窗
     */
    private PopupWindow zhuiYiOrderWindow;
    private LinearLayout zhuiYiOrderLayout;
    private CheckBox zhuiyiProductOrderTextView;
    private CheckBox zhuiyiLoanOrderTextView;
    private ListView zhuiYiOrderListView;
    private View zhuiYiOrderHeaderView;
    private ZhuiyiProductOrderListAdapter zhuiYiProductOrderListAdapter;
    private ZhuiyiLoanOrderListAdapter zhuiyiLoanOrderListAdapter;
    private SwipeRefreshLayout zhuiYiOrderSwipeRefreshLayout;
    public View zhuiYiOrderLoadingView;
    public List<ZhuiyiProductOrderEntity> zhuiYiProductOrderList = new ArrayList<ZhuiyiProductOrderEntity>();
    public List<ZhuiyiLoanOrderEntity> zhuiYiLoanOrderList = new ArrayList<ZhuiyiLoanOrderEntity>();
    public boolean isZhuiYiOrderListNeedRefresh = true;
    private boolean hasMoreZhuiYiOrderList = false;
    boolean isZhuiYiOrderListLoading = false;
    boolean isZhuiyiProductListPage = true;
    public ImageView zhuiyiOrderTitleGap;
    public String currentZhuiyiOrderQuestion;
    public boolean isSendQuiteMsg = true;

    /**显示追一订单窗口**/
    @Override
    public void showZhuiyiOrderList(String jxQuestion, final boolean productOrderEnable, final boolean loanOrderEnable){
        currentZhuiyiOrderQuestion = jxQuestion;
        isSendQuiteMsg = true;
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mContext == null) {
                    return;
                }
                if (zhuiYiOrderLayout == null) {
                    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE);
                    zhuiYiOrderLayout = (LinearLayout) inflater.inflate(R.layout.jx_zhui_order_pop_window,
                            null);
                    zhuiyiProductOrderTextView = zhuiYiOrderLayout.findViewById(R.id.tv_zhuiyi_product_order_list_title);
                    zhuiyiLoanOrderTextView = zhuiYiOrderLayout.findViewById(R.id.tv_zhuiyi_loan_order_list_title);
                    zhuiyiOrderTitleGap = zhuiYiOrderLayout.findViewById(R.id.iv_zhuiyi_order_list_title_gap);
                    zhuiYiOrderSwipeRefreshLayout = (SwipeRefreshLayout) zhuiYiOrderLayout.findViewById(R.id.zhuiyi_order_pop_window_refresh);
                    zhuiYiOrderListView = (ListView) zhuiYiOrderLayout.findViewById(R.id.lv_zhuiyi_order_pop_window);
                    zhuiYiOrderSwipeRefreshLayout.setColorSchemeResources(R.color.jx_title_bar);
                    zhuiYiOrderSwipeRefreshLayout.setOnRefreshListener(zhuiyiOrderRefreshListener);
                    zhuiYiOrderLoadingView = inflater.inflate(R.layout.jx_item_common_list_loadingview, null);
                    zhuiYiOrderListView.setOnScrollListener(zhuiyiOrderListScrollListener);
                    zhuiyiProductOrderTextView.setOnClickListener(zhuiyiProductOrderClickListener);
                    zhuiyiLoanOrderTextView.setOnClickListener(zhuiyiLoanOrderClickListener);
                }

                zhuiyiOrderTitleGap.setVisibility(View.VISIBLE);
                if (productOrderEnable){
                    zhuiyiProductOrderTextView.setVisibility(View.VISIBLE);
                    isZhuiyiProductListPage = true;
                    zhuiyiProductOrderTextView.setChecked(true);
                }else {
                    zhuiyiOrderTitleGap.setVisibility(View.GONE);
                    zhuiyiProductOrderTextView.setVisibility(View.GONE);
                    isZhuiyiProductListPage = false;
                    zhuiyiProductOrderTextView.setChecked(false);
                }
                if (loanOrderEnable){
                    zhuiyiLoanOrderTextView.setVisibility(View.VISIBLE);
                    zhuiyiLoanOrderTextView.setChecked(true);
                }else {
                    zhuiyiOrderTitleGap.setVisibility(View.GONE);
                    zhuiyiLoanOrderTextView.setVisibility(View.GONE);
                    zhuiyiLoanOrderTextView.setChecked(false);
                }
                if (productOrderEnable && loanOrderEnable){
                    zhuiyiProductOrderTextView.setChecked(true);
                    zhuiyiLoanOrderTextView.setChecked(false);
                }
                // 创建PopupWindow对象
                if (zhuiYiOrderWindow == null) {
                    zhuiYiProductOrderListAdapter = new ZhuiyiProductOrderListAdapter(mContext, new ArrayList<ZhuiyiProductOrderEntity>());
                    zhuiyiLoanOrderListAdapter = new ZhuiyiLoanOrderListAdapter(mContext, new ArrayList<ZhuiyiLoanOrderEntity>());
                    zhuiYiOrderListView.setAdapter(zhuiYiProductOrderListAdapter);
                    zhuiYiOrderListView.setOnItemClickListener(zhuiyiOrderItemListener);
                    zhuiYiOrderWindow = new PopupWindow(zhuiYiOrderLayout, LayoutParams
                            .MATCH_PARENT,
                            LayoutParams.WRAP_CONTENT, false);
                    zhuiYiOrderWindow.setBackgroundDrawable(new ColorDrawable(0));
                    // 设置点击窗口外边窗口消失
                    zhuiYiOrderWindow.setOutsideTouchable(true);
                    zhuiYiOrderWindow.setFocusable(true);
                    zhuiYiOrderWindow.setAnimationStyle(R.style.JXAnimationPreview);
                    zhuiYiOrderWindow.setOnDismissListener(zhuiyiOrderListDismissListener);
                }
                zhuiYiOrderWindow.showAtLocation(rootLayout,
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                if (inputMethodManager.isActive()) {
                    inputMethodManager.hideSoftInputFromWindow(menuLayout.contentText
                            .getWindowToken(), 0);
                }
                zhuiYiOrderSwipeRefreshLayout.post(new Runnable() {
                    public void run() {
                        zhuiYiOrderSwipeRefreshLayout.setRefreshing(true);
                    }
                });
                hasMoreZhuiYiOrderList = false;
                isZhuiYiOrderListLoading = true;
                if (zhuiYiOrderListView.getFooterViewsCount()>0) {
                    zhuiYiOrderListView.removeFooterView(zhuiYiOrderLoadingView);
                }
                zhuiYiOrderListView.setSelection(0);
                zhuiyiOrderRefreshListener.onRefresh();
            }
        });
    }

    PopupWindow.OnDismissListener zhuiyiOrderListDismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            if (mContext == null || !isAdded()) {
                return;
            }
            zhuiYiOrderSwipeRefreshLayout.setRefreshing(false);
            hasMoreOrderList = false;
            zhuiYiProductOrderList.clear();
            zhuiYiLoanOrderList.clear();
            zhuiYiOrderListView.setAdapter(zhuiYiProductOrderListAdapter);
            zhuiYiProductOrderListAdapter.refresh(zhuiYiProductOrderList);
            if (isSendQuiteMsg){
                chatPresenter.sendTextMessage(getString(R.string.jx_left_out));
            }
        }
    };

    @Override
    public void refreshZhuiyiProductOrderList(List<ZhuiyiProductOrderEntity> refreshOrderList, boolean hasMore, boolean refresh){
        if (mContext == null || !isAdded()) {
            return;
        }
        hasMoreZhuiYiOrderList = hasMore;
        isZhuiYiOrderListLoading = false;
        if (mContext !=null && zhuiYiOrderWindow.isShowing()&&isZhuiyiProductListPage){
            if (zhuiYiOrderListView.getFooterViewsCount()>0) {
                zhuiYiOrderListView.removeFooterView(zhuiYiOrderLoadingView);
            }
            if (refresh){
                //刷新
                zhuiYiOrderSwipeRefreshLayout.setRefreshing(false);
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    zhuiYiProductOrderList.clear();
                    zhuiYiProductOrderList.addAll(refreshOrderList);
                    zhuiYiProductOrderListAdapter.refresh(zhuiYiProductOrderList);
                    zhuiYiOrderListView.setAdapter(zhuiYiProductOrderListAdapter);
                    zhuiYiOrderListView.setSelection(0);
                }else {
                    JXCommonUtils.showToast(mContext,mContext.getString(R.string.jx_can_not_find_order));
                }
            }else {
                //加载更多
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    int w_cur_pos=zhuiYiOrderListView.getFirstVisiblePosition();
                    this.zhuiYiProductOrderList.addAll(refreshOrderList);
                    zhuiYiProductOrderListAdapter.refresh(this.zhuiYiProductOrderList);
                    zhuiYiOrderListView.setAdapter(zhuiYiProductOrderListAdapter);
                    zhuiYiOrderListView.setSelection(w_cur_pos);
                }
            }
            if (hasMore){
                zhuiYiOrderListView.addFooterView(zhuiYiOrderLoadingView, null, false);
            }
        }
    }

    @Override
    public void refreshZhuiyiLoanOrderList(List<ZhuiyiLoanOrderEntity> refreshOrderList, boolean hasMore, boolean refresh){
        if (mContext == null || !isAdded()) {
            return;
        }
        hasMoreZhuiYiOrderList = hasMore;
        isZhuiYiOrderListLoading = false;
        if (mContext !=null && zhuiYiOrderWindow.isShowing() && !isZhuiyiProductListPage){
            if (zhuiYiOrderListView.getFooterViewsCount()>0) {
                zhuiYiOrderListView.removeFooterView(zhuiYiOrderLoadingView);
            }
            if (refresh){
                //刷新
                zhuiYiOrderSwipeRefreshLayout.setRefreshing(false);
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    zhuiYiLoanOrderList.clear();
                    zhuiYiLoanOrderList.addAll(refreshOrderList);
                    zhuiyiLoanOrderListAdapter.refresh(refreshOrderList);
                    zhuiYiOrderListView.setAdapter(zhuiyiLoanOrderListAdapter);
                    zhuiYiOrderListView.setSelection(0);
                }else {
                    JXCommonUtils.showToast(mContext,mContext.getString(R.string.jx_can_not_find_order));
                }
            }else {
                //加载更多
                if (refreshOrderList != null && refreshOrderList.size()>0){
                    int w_cur_pos=zhuiYiOrderListView.getFirstVisiblePosition();
                    this.zhuiYiLoanOrderList.addAll(refreshOrderList);
                    zhuiyiLoanOrderListAdapter.refresh(this.zhuiYiLoanOrderList);
                    zhuiYiOrderListView.setAdapter(zhuiyiLoanOrderListAdapter);
                    zhuiYiOrderListView.setSelection(w_cur_pos);
                }
            }
            if (hasMore){
                zhuiYiOrderListView.addFooterView(zhuiYiOrderLoadingView, null, false);
            }
        }
    }

    public AbsListView.OnScrollListener zhuiyiOrderListScrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // 当滚到最后一行且停止滚动时，执行加载
            if (view.getLastVisiblePosition() == view.getCount() - 1
                    && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                    && hasMoreZhuiYiOrderList && !isZhuiYiOrderListLoading) {
                isZhuiYiOrderListLoading = true;
                if (isZhuiyiProductListPage){
                    chatPresenter.fetchZhuiyiProductList(false);
                }else {
                    chatPresenter.fetchZhuiyiLoanList(false);
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int
                totalItemCount) {

        }
    };

    public OnRefreshListener zhuiyiOrderRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh() {
            if (isZhuiyiProductListPage){
                chatPresenter.fetchZhuiyiProductList(true);
            }else {
                chatPresenter.fetchZhuiyiLoanList(true);
            }
        }
    };

    OnItemClickListener zhuiyiOrderItemListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            isSendQuiteMsg = false;
            if(isZhuiyiProductListPage){
                ZhuiyiProductOrderEntity zhuiyiProductOrderEntity = (ZhuiyiProductOrderEntity) zhuiYiProductOrderListAdapter.getItem(position);
                chatPresenter.sendZhuiyiProductOrderMessage(zhuiyiProductOrderEntity,currentZhuiyiOrderQuestion);
            }else {
                ZhuiyiLoanOrderEntity loanOrderEntity = (ZhuiyiLoanOrderEntity) zhuiyiLoanOrderListAdapter.getItem(position);
                chatPresenter.sendZhuiyiLoantOrderMessage(loanOrderEntity,currentZhuiyiOrderQuestion);
            }
            if (zhuiYiOrderWindow != null && zhuiYiOrderWindow.isShowing()) {
                zhuiYiOrderWindow.dismiss();
            }
        }
    };

    View.OnClickListener zhuiyiProductOrderClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isZhuiyiProductListPage){
                zhuiyiProductOrderTextView.setChecked(true);
                return;
            }
            isZhuiyiProductListPage = true;
            zhuiyiProductOrderTextView.setChecked(true);
            zhuiyiLoanOrderTextView.setChecked(false);
            if (zhuiYiOrderListView.getFooterViewsCount()>0) {
                zhuiYiOrderListView.removeFooterView(zhuiYiOrderLoadingView);
            }
            zhuiYiOrderListView.setAdapter(zhuiYiProductOrderListAdapter);
            zhuiYiOrderSwipeRefreshLayout.setRefreshing(true);
            chatPresenter.fetchZhuiyiProductList(true);
        }

    };

    View.OnClickListener zhuiyiLoanOrderClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isZhuiyiProductListPage){
                zhuiyiLoanOrderTextView.setChecked(true);
                return;
            }
            isZhuiyiProductListPage = false;
            zhuiyiProductOrderTextView.setChecked(false);
            zhuiyiLoanOrderTextView.setChecked(true);
            if (zhuiYiOrderListView.getFooterViewsCount()>0) {
                zhuiYiOrderListView.removeFooterView(zhuiYiOrderLoadingView);
            }
            zhuiYiOrderListView.setAdapter(zhuiyiLoanOrderListAdapter);
            zhuiYiOrderSwipeRefreshLayout.setRefreshing(true);
            chatPresenter.fetchZhuiyiLoanList(true);
        }

    };

    public void handleWaitTipsOption(){
        String str1 = getString(R.string.jx_cancel_wait_tipsline);
        JXLinkMovementMethod movementMethod = JXLinkMovementMethod.getInstance();
        cancelTipsTextView.setMovementMethod(movementMethod);
        Spanned spanned = Html.fromHtml(str1, null, null);
        cancelTipsTextView.setText(spanned);
        CharSequence str = cancelTipsTextView.getText();
        int end = str.length();
        SpannableString sp = new SpannableString(str);
        URLSpan[] urls=sp.getSpans(0, end, URLSpan.class);  //找出text中的a标签
        if (urls != null && urls.length > 0){
            SpannableStringBuilder style=new SpannableStringBuilder(str);
            for(URLSpan url : urls){
                String urlStr = url.getURL();
                MyURLSpan myURLSpan = new MyURLSpan(urlStr);
                style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(myURLSpan,sp.getSpanStart(url),sp.getSpanEnd(url),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.removeSpan(url);
            }
            cancelTipsTextView.setText(style,TextView.BufferType.SPANNABLE);
        }
    }

    private class MyURLSpan extends ClickableSpan {

        private String url;

        public MyURLSpan(String url) {
            this.url = url;
        }

        @Override
        public void onClick(View arg0) {
            JXLog.d("[JXBaseChatFragment.MyURLSpan] , on click url text = "+url+" , vid = "+arg0.getId());
            processWaitTipsOption(url);
        }

    }

}
